package world.zwq.gulimall.product.exception;


import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import world.zwq.common.exception.BaseCodeEnum;
import world.zwq.common.utils.R;

import java.util.HashMap;
import java.util.Map;

@RestControllerAdvice(basePackages = "world.zwq.gulimall.product.controller")
@Slf4j
public class GulimallExceptionControllerAdvice {


    @ExceptionHandler(value = {MethodArgumentNotValidException.class})
    public R handleValidException(MethodArgumentNotValidException e) {
        log.error("数据校验异常{},异常类型{}", e.getMessage(), e.getClass(), e);
        BindingResult result = e.getBindingResult();
        //获取错误的校验结果
        Map<String, String> map = new HashMap<>();
        result.getFieldErrors().forEach(fieldError -> {
            //获取错误提示
            String defaultMessage = fieldError.getDefaultMessage();
            String field = fieldError.getField();
            map.put(field, defaultMessage);
        });
        return R.error(BaseCodeEnum.VALID_EXCEPTION.getCode(), BaseCodeEnum.VALID_EXCEPTION.getMsg()).put("data", map);
    }

    @ExceptionHandler(value = Throwable.class)
    public R handleException(Throwable throwable){
        return R.error(BaseCodeEnum.UNKNOW_EXCEPTION.getCode(), BaseCodeEnum.UNKNOW_EXCEPTION.getMsg());
    }
}
